package org.mcjug.locationmailer.oauth.tokens;

import java.net.URLEncoder;

import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;

import org.mcjug.locationmailer.R;
import org.mcjug.locationmailer.activity.BaseActivity;
import org.mcjug.locationmailer.activity.LocationMailerActivity;
import org.mcjug.locationmailer.activity.SignInActivity;
import org.mcjug.locationmailer.util.Constants;
import org.mcjug.locationmailer.util.ExceptionUtil;
import org.mcjug.locationmailer.util.NetworkConnectivity;
import org.mcjug.locationmailer.util.RunnableWithException;

import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.Toast;
//import android.util.Log;

public class OauthActivity extends BaseActivity {
    private final String TAG = getClass().getSimpleName();

    private CommonsHttpOAuthConsumer consumer;
    private CommonsHttpOAuthProvider provider;
    private OAuthRequestTokenTask oAuthRequestTokenTask;
    private RetrieveAccessTokenTask retrieveAccessTokenTask;

    protected void onCreate(Bundle savedInstanceState) {
        try {
           super.onCreate(savedInstanceState);
           
	       	if (!NetworkConnectivity.isAvailable(this)) {
	    		// Go back to sign-in screen
	    		startActivity(new Intent().setClass(getApplicationContext(), SignInActivity.class).setFlags(
	                    Intent.FLAG_ACTIVITY_NEW_TASK));
	    		return;
	    	}	    	

            // you must have a file called secret.xml under /res/values with the key
            // and
            // secret for this to work
            String scope = Constants.getProperty(this, R.string.oauthScopePreferenceName,
                    R.string.oauthScopeDefaultValue);
            String consumerKey = Constants.getProperty(this, R.string.oauthConsumerKeyPreferenceName,
                    R.string.oauthConsumerKeyDefaultValue);
            String consumerSecret = Constants.getProperty(this, R.string.oauthConsumerSecretPreferenceName,
                    R.string.oauthConsumerSecretDefaultValue);
            consumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
            //Log.d(TAG, "Create provider");

            String requestTokenEndpointUrl = Constants.getProperty(this,
                    R.string.requestTokenEndpointUrlPreferenceName, R.string.requestTokenEndpointUrlDefaultValue);
            String accessTokenEndpointUrl = Constants.getProperty(this, R.string.accessTokenEndpointUrlPreferenceName,
                    R.string.accessTokenEndpointUrlDefaultValue);
            String authorizationWebsiteUrl = Constants.getProperty(this,
                    R.string.authorizationWebsiteUrlPreferenceName, R.string.authorizationWebsiteUrlDefaultValue);
            provider = new CommonsHttpOAuthProvider(requestTokenEndpointUrl + URLEncoder.encode(scope, "utf-8")
                    + "&xoauth_displayname=" + URLEncoder.encode(getString(R.string.app_name), "utf-8"),
                    accessTokenEndpointUrl, authorizationWebsiteUrl);

            //Log.d(TAG, "Before create and execute OAuthRequestTokenTask");
            oAuthRequestTokenTask = new OAuthRequestTokenTask(this, consumer, provider);
            oAuthRequestTokenTask.execute();
            //Log.d(TAG, "After create and execute OAuthRequestTokenTask");
        } catch (Throwable e) {
            //Log.e(TAG, "OauthActivity onCreate error", e);
            ExceptionUtil.exceptAway(this, e, "OauthActivity onCreate error: ", new RunnableWithException() {

                @Override
                public void run() throws Throwable {
                    //Log.d(TAG, "About to clean up after OauthActivity onCreate error");
                    if (oAuthRequestTokenTask != null) {
                        oAuthRequestTokenTask.cancel(true);
                        oAuthRequestTokenTask = null;
                    }
                    //Log.d(TAG, "Done cleaning up after OauthActivity onCreate error");
                }
            });
        }
    }

    protected void onNewIntent(Intent intent) {
        try {
            super.onNewIntent(intent);
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
            final Uri uri = intent.getData();
            if (uri != null
                    && uri.getScheme().equals(
                            Constants.getProperty(this, R.string.oauthCallbackUrlPreferenceName,
                                    R.string.oauthCallbackSchemeDefaultValue))) {
                //Log.i(TAG, "Callback received : " + uri);
                //Log.i(TAG, "Retrieving Access Token");
                retrieveAccessTokenTask = new RetrieveAccessTokenTask(this, consumer, provider, prefs,
                        new RunnableWithException() {

                            @Override
                            public void run() throws Throwable {
                                //Log.d(TAG, "After creating and executing RetrieveAccessTokenTask");
                                startActivity(new Intent().setClass(getApplicationContext(),
                                        LocationMailerActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                                finish();
                            }
                        });
                retrieveAccessTokenTask.execute(uri);
                //Log.d(TAG, "After calling finish on OauthActivity");
            }
        } catch (Throwable e) {
            //Log.e(TAG, "OauthActivity onNewIntent error", e);
            ExceptionUtil.exceptAway(this, e, "OauthActivity onNewIntent error: ", new RunnableWithException() {

                @Override
                public void run() throws Throwable {
                    //Log.d(TAG, "About to clean up after OauthActivity onNewIntent error");
                    if (retrieveAccessTokenTask != null) {
                        retrieveAccessTokenTask.cancel(true);
                        retrieveAccessTokenTask = null;
                    }
                    //Log.d(TAG, "Done cleaning up after OauthActivity onNewIntent error");
                }
            });
        }
    }
}
